import React, { useEffect, useState } from 'react'
import {
  Button,
  message,
  Space,
  Table,
  Dropdown,
  Checkbox,
  Drawer,
  Empty,
  Modal,
  notification,
  Form,
  DatePicker,
  Spin,
} from 'antd'
import useGetTableData from '@/hooks/useGetTableData'
import SearchForm from '@/components/CustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useIndexColumns, useInnerColumns } from './columns'
import { ITableData, ReserveInvoiceDetailVO } from './types'
import { EditFormVertical } from '@/components/CustomForm'
import CustomTable from '@/components/CustomTable'
import {
  applicationTypeEnum,
  OperationDeliveryActionsType,
  OperationLogType,
  PUSH_STATE_STATUS_OPTIONS,
} from '@/constant'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { useAppSelector } from '@/store/hooks'
import './index.less'
import { DownOutlined, ExclamationCircleOutlined, UploadOutlined } from '@ant-design/icons'
import { ORDER_SOURCE_OPTIONS, RESERVE_INVOICE_STATUS_OPTIONS } from '@/constant/purchase'
import { getProductClassConfigByType, getSpuOptions, reserveInvoiceExport } from '@/api/goods'
import dayjs from 'dayjs'
import {
  exportOutNoticeOrder,
  reserveInvoiceBatchAudit,
  reserveInvoicebatchCancel,
  reserveInvoiceDelivery,
  reserveInvoicePush,
  reserveInvoiceQuery,
  submitBoxLoad,
} from '@/api/purchase'
import { useFormDelivery, useFormViewDelivery } from './useForm'
import { getSupplierList } from '@/api/supplier'
import { downloadByOwnUrl, exportNotification, getRecentThreeMonths } from '@/utils/util'
import useSearchUser from '@/hooks/useSearchUser'
import { onValuesChange } from '@/utils/onValuesChange'
import LogsDrawer from '@/components/LogsDrawer'
import useViewLogs from '@/hooks/useViewLogs'
import PermissionButton from '@/components/PermissionButton'
import useSearchSupplier from '@/hooks/useSearchSupplier'
import useCachePage from '@/hooks/useCachePage'
const Index: React.FC = () => {
  let SpuTimeout: ITimeoutType
  const navigate = useNavigate()
  const [form] = useForm()
  const [FormDelivery] = useForm()
  const [FormViewDelivery] = useForm()
  const [FormSend] = useForm()
  const DICTDATA = useAppSelector((state) => state.login.DICTDATA)
  const [deliveryModalShow, setdeliveryModalShow] = useState<boolean>(false)
  const [expand, setexpand] = useState<boolean>(false)
  const [selectedRowKeys, setselectedRowKeys] = useState<React.Key[]>([])
  const [selectedRowInfos, setselectedRowInfos] = useState<ITableData[]>([])
  const [SpuOptions, setSpuOptions] = useState<IOptionItem[]>([])
  const [SkuOptions, setSkuOptions] = useState<IOptionItem[]>([])
  const [exportLoading, setexportLoading] = useState(false)
  const [isModalShow, setisModalShow] = useState<boolean>(false)
  const [spinning, setspinning] = useState<boolean>(false)
  //大类
  const [classBig, setclassBig] = useState<IOptionItem[]>([])
  const [CurrentInfo, setCurrentInfo] = useState<Record<string, any>>({})
  // 日志
  const { isLogShow, setisLogShow, logLoading, logInfos, setLogInfos, viewLogs } = useViewLogs(
    'reserveInvoiceCode',
    OperationLogType.RESERVEINVOICE,
  )
  // 承运商
  const [SupplierCYOption, setSupplierCYOption] = useState<IOptionItem[]>([])
  const [expandedRowKeys, setexpandedRowKeys] = useState<React.Key[]>([])
  const [viewdeliveryModalShow, setviewdeliveryModalShow] = useState(false)
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const [menuItems, setmenuItems] = useState<{ key: string; label: string }[]>([])
  const { SupplierOption, handleSearchSupplier, setSupplierOption } = useSearchSupplier('supplierId')
  const applicationId = useAppSelector((state) => state.user.user_info.applicationId)
  const isRoot = applicationId == applicationTypeEnum.SOP_SEVENFUN_WEB
  const defaultDateRange = getRecentThreeMonths()
  const { UserOptions, handleSearchUser, setUserOptions } = useSearchUser()
  const [query] = useSearchParams()
  const reserveInvoiceCode = query.get('reserveInvoiceCode') || ''
  const { setCachePage, getCachePage } = useCachePage()
  const { tableProps, params, setParams, search, reset } = useGetTableData<ITableData>(reserveInvoiceQuery, {
    form: form,
    defaultFieldsParams: {
      createTimeStart: defaultDateRange,
      reserveInvoiceStatuses: [1, 2, 3, 4, 6],
      reserveInvoiceCodes: reserveInvoiceCode ? [reserveInvoiceCode] : null,
    },
    immediatelySend: false,
    cachePageCallback: (current, size, prevSize) => {
      const cacheData = getCachePage()
      setCachePage({
        ...cacheData,
        current: prevSize === size ? current : 1,
        size,
      })
    },
  })
  useEffect(() => {
    getProductClassConfig()
    getSupList('')
    handleCacheData()
  }, [])
  useEffect(() => {
    const items: { key: string; label: string }[] = []
    if (buttonCodeList.includes('pushDeliver')) {
      items.push({
        key: 'PUSH',
        label: '触发CB推送',
      })
    }
    setmenuItems(items)
    const data = tableProps.dataSource.map((item) => item.reserveInvoiceId)
    if (expand) {
      setexpandedRowKeys(data)
    } else {
      setexpandedRowKeys([])
    }
  }, [tableProps.dataSource, expand])
  const handleCacheData = () => {
    const cacheData = getCachePage()
    if (cacheData == null || reserveInvoiceCode) {
      const paramsData = {
        ...params,
        createTimeStart: dayjs(defaultDateRange[0]).format('YYYY-MM-DD HH:mm:ss'),
        createTimeEnd: dayjs(defaultDateRange[1]).format('YYYY-MM-DD HH:mm:ss'),
        reserveInvoiceStatuses: [1, 2, 3, 4, 6],
      }
      search({
        ...paramsData,
      })
      setCachePage({
        ...paramsData,
      })
    } else {
      form.setFieldsValue({
        ...cacheData,
        createTimeStart:
          cacheData.createTimeStart && cacheData.createTimeEnd
            ? [dayjs(cacheData.createTimeStart), dayjs(cacheData.createTimeEnd)]
            : null,
        scheduleDeliveryTimeStart:
          cacheData.scheduleDeliveryTimeStart && cacheData.scheduleDeliveryTimeEnd
            ? [dayjs(cacheData.scheduleDeliveryTimeStart), dayjs(cacheData.scheduleDeliveryTimeEnd)]
            : null,
        estimatedArrivalTimeStart:
          cacheData.estimatedArrivalTimeStart && cacheData.estimatedArrivalTimeEnd
            ? [dayjs(cacheData.estimatedArrivalTimeStart), dayjs(cacheData.estimatedArrivalTimeEnd)]
            : null,
        lastArrivalTimeStart:
          cacheData.lastArrivalTimeStart && cacheData.lastArrivalTimeEnd
            ? [dayjs(cacheData.lastArrivalTimeStart), dayjs(cacheData.lastArrivalTimeEnd)]
            : null,
        reserveInvoiceStatuses: cacheData.reserveInvoiceStatuses != null ? cacheData.reserveInvoiceStatuses : null,
        orderSources: cacheData.orderSources && cacheData.orderSources.length > 0 ? cacheData.orderSources[0] : null,
        reserveInvoiceCodes: cacheData?.reserveInvoiceCodes != null ? cacheData.reserveInvoiceCodes : null,
        purchaseOrderCodes: cacheData?.purchaseOrderCodes != null ? cacheData.purchaseOrderCodes : null,
      })
      setSpuOptions(cacheData?.SpuOptions || [])
      setSupplierOption(cacheData?.SupplierOption || [])
      setUserOptions(cacheData?.UserOptions || [])
      delete cacheData.SpuOptions
      delete cacheData.SupplierOption
      delete cacheData.UserOptions
      search({
        ...cacheData,
        createTimeStart: cacheData.createTimeStart ? cacheData.createTimeStart : null,
        createTimeEnd: cacheData.createTimeEnd ? cacheData.createTimeEnd : null,
        pushStatus: isRoot ? cacheData.pushStatus : null,
        trackOrderPerson: isRoot ? (cacheData.trackOrderPerson ? cacheData.trackOrderPerson : null) : null,
        reserveInvoiceCodes: cacheData?.reserveInvoiceCodes != null ? cacheData.reserveInvoiceCodes : null,
        purchaseOrderCodes: cacheData?.purchaseOrderCodes != null ? cacheData.purchaseOrderCodes : null,
      })
    }
  }
  const onCancel = () => {
    setCurrentInfo({})
    setdeliveryModalShow(false)
    setviewdeliveryModalShow(false)
    FormDelivery.resetFields()
    setisModalShow(false)
    FormSend.resetFields()
  }
  const selectRows = (keys: React.Key[], info: ITableData[]) => {
    setselectedRowKeys(keys)
    setselectedRowInfos(info)
  }
  const expandedRowRender = (rows: ReserveInvoiceDetailVO) => {
    return (
      <Table
        rowKey={(rows) => rows.reserveInvoiceDetailId}
        columns={useInnerColumns()}
        dataSource={rows.detailVOS || []}
        pagination={false}
        scroll={{
          x: 'max-content',
        }}
        rowHoverable={false}
        rowClassName={(record, index) => {
          return index % 2 === 0 ? '' : 'zebra-row-odd'
        }}
      />
    )
  }
  const getProductClassConfig = async (type: 1 | 2 | 3 | 4 = 1) => {
    const res = await getProductClassConfigByType<{
      className: string
      classConfigId: string | number
    }>({ type, auth: 1 })
    const classIdOptions =
      res?.data?.map((item) => {
        return {
          label: item.className,
          value: item.classConfigId,
          isLeaf: false,
        }
      }) || []
    setclassBig(classIdOptions)
  }
  const handleSearchSpuOptions = (newValue = '') => {
    if (!newValue) return
    if (SpuTimeout) {
      clearTimeout(SpuTimeout)
      SpuTimeout = null
    }
    const getOptions = async () => {
      const res = await getSpuOptions<{
        spuName: string
        spuCode: string
        designCode: string
      }>({ keyword: newValue })
      if (res.code === 200) {
        const data =
          res?.data?.map((item) => {
            return {
              label: `${item?.spuCode}｜${item.spuName}${item?.designCode ? '｜' + item?.designCode : ''}`,
              value: item.spuCode,
            }
          }) || []
        setSpuOptions(data)
      }
    }
    SpuTimeout = setTimeout(getOptions, 500)
  }
  const onView = (info: ITableData) => {
    setCurrentInfo(info)
    setviewdeliveryModalShow(true)
  }
  const onViewLogs = (info: ITableData) => {
    viewLogs(info)
  }
  const onConfirmDelivery = (info: ITableData) => {
    setCurrentInfo(info)
    setdeliveryModalShow(true)
  }
  const onSubmitPacking = (info: ITableData) => {
    setCurrentInfo(info)
    setisModalShow(true)
  }
  const onDel = async (info: ITableData) => {
    const instance = Modal.confirm({
      title: '提示',
      content: (
        <div style={{ color: 'red' }}>取消预约后，无法再对订单执行任何操作，订单下的箱唛将失效，确认要操作吗?</div>
      ),
      okText: '确认',
      cancelText: '取消',
      icon: <ExclamationCircleOutlined />,
      onOk: async () => {
        const res = await reserveInvoicebatchCancel({
          cancelDetails: [{ reserveInvoiceCode: info.reserveInvoiceCode, orderSource: info.orderSource }],
        }).finally(() => {
          instance.destroy()
          search(params)
        })
        if (res.code === 200) {
          message.success('操作成功')
        }
        if (res.code === 820000 && res.failInfo) {
          const failInfo = JSON.parse(res.failInfo)?.map((item: { failCode: string; failMsg: string }) => {
            return (
              <div key={item.failCode + item.failMsg}>
                {item.failCode}，{item.failMsg}
              </div>
            )
          })
          notification.open({
            type: 'warning',
            message: res.msg,
            description: failInfo,
          })
        }
      },
    })
  }
  const getSupList = async (newValue: string) => {
    const res = await getSupplierList<{ supplierName: string; supplierId: string }>({
      supplierClassificationCode: '承运商',
      keyword: newValue,
      useStatus: 1,
      // 0 不鉴权
      authSupplier: 0,
    })
    if (res.code === 200) {
      const SupplierCYOption =
        res?.data?.list?.map((item) => {
          return {
            label: item.supplierName,
            value: item.supplierId,
          }
        }) || []
      setSupplierCYOption(SupplierCYOption)
    }
  }
  const onDelivery = async (values: any) => {
    const paramsData = {
      ...values,
      estimatedArrivalTime: values.estimatedArrivalTime && dayjs(values.estimatedArrivalTime).format('YYYY-MM-DD'),
      reserveInvoiceCode: CurrentInfo.reserveInvoiceCode,
    }
    const res = await reserveInvoiceDelivery(paramsData).finally(() => {
      search(params)
      onCancel()
    })
    if (res.code === 200) {
      message.success('操作成功')
    }
    if (res.code === 820000 && res.failInfo) {
      const failInfo = JSON.parse(res.failInfo)?.map((item: string) => {
        return <div key={item}>{item}</div>
      })
      notification.open({
        type: 'warning',
        message: res.msg,
        description: failInfo,
      })
    }
  }
  const handleClickMore = async (info: any) => {
    if (selectedRowKeys.length === 0) {
      message.warning('请勾选需要操作的列表数据！')
      return
    }
    if (info.key == 'PUSH') {
      const res = await reserveInvoicePush({
        reserveInvoiceCodes: selectedRowInfos.map((item) => item.reserveInvoiceCode),
      })
      if (res.code === 200) {
        message.success('触发推送成功，请稍后查看！')
        setselectedRowKeys([])
        setselectedRowInfos([])
        search(params)
      }
    }
  }
  const onSendOk = async () => {
    const data = await FormSend.validateFields()
    const paramData = {
      purchaseOrderCode: CurrentInfo?.detailVOS[0]?.purchaseOrderCode,
      reserveInvoiceCode: CurrentInfo.reserveInvoiceCode,
      scheduleDeliveryTime:
        data?.scheduleDeliveryTime && dayjs(data.scheduleDeliveryTime).format('YYYY-MM-DD HH:mm:ss'),
    }
    const res = await submitBoxLoad(paramData)
    if (res.code === 200) {
      message.success('操作成功')
      search(params)
      onCancel()
    }
  }
  return (
    <PageContainer className="purchase_delivery_page">
      <SearchForm
        params={params}
        form={form}
        // onValuesChange={(changedValues) => onValuesChange(changedValues, [''], form)}
        searchConfig={[
          {
            label: '预约发货单号',
            name: 'reserveInvoiceCodes',
            placeholder: '多个单号间需要换行或使用","分隔',
            type: 'Select',
            config: {
              mode: 'tags',
              maxTagCount: 'responsive',
              tokenSeparators: [',', '，', '\n', '\r', '\r\n'],
              notFoundContent: null,
            },
          },
          { label: '制单时间', name: 'createTimeStart', type: 'RangePicker', config: { showTime: true } },
          {
            label: '订单状态',
            name: 'reserveInvoiceStatuses',
            type: 'Select',
            option: RESERVE_INVOICE_STATUS_OPTIONS,
            config: {
              suffixIcon: null,
              showSearch: true,
              optionFilterProp: 'label',
              mode: 'multiple',
              maxTagCount: 'responsive',
            },
          },
          { label: '预约发货时间', name: 'scheduleDeliveryTimeStart', type: 'RangePicker', config: { showTime: true } },
          {
            label: '大类',
            name: 'bigClassIds',
            type: 'Select',
            option: classBig,
            config: {
              mode: 'multiple',
              maxTagCount: 'responsive',
              optionFilterProp: 'label',
            },
          },
          {
            name: 'supplierIds',
            label: '供应商',
            type: 'Select',
            option: SupplierOption,
            config: {
              suffixIcon: null,
              showSearch: true,
              optionFilterProp: 'label',
              filterOption: false,
              mode: 'multiple',
              maxTagCount: 'responsive',
              onSearch: handleSearchSupplier,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
            },
          },
          {
            label: '采购订单号',
            name: 'purchaseOrderCodes',
            placeholder: '多个单号间需要换行或使用","分隔',
            type: 'Select',
            config: {
              mode: 'tags',
              maxTagCount: 'responsive',
              tokenSeparators: [',', '，', '\n', '\r', '\r\n'],
              notFoundContent: null,
            },
          },
          {
            label: '年份',
            name: 'year',
            type: 'FixedDatePicker',
            placeholder: '请选择年份',
            config: {
              picker: 'year',
              format: 'YYYY',
              customFormat: 'YYYY',
            },
          },
          {
            name: 'seasonCode',
            label: '订单季节',
            type: 'Select',
            option: DICTDATA.order_season,
            placeholder: '请选择订单季节',
            config: {
              showSearch: true,
              optionFilterProp: 'label',
            },
          },
          { label: '预计到货时间', name: 'estimatedArrivalTimeStart', type: 'RangePicker', config: { showTime: true } },
          { label: '最近到货时间', name: 'lastArrivalTimeStart', type: 'RangePicker', config: { showTime: true } },
          { label: '订单来源', name: 'orderSources', type: 'Select', option: ORDER_SOURCE_OPTIONS },
          {
            label: '供应链跟单',
            name: 'trackOrderPerson',
            type: 'Select',
            option: UserOptions,
            hidden: !isRoot,
            config: {
              suffixIcon: null,
              showSearch: true,
              optionFilterProp: 'label',
              filterOption: false,
              onSearch: handleSearchUser,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
              fieldNames: { label: 'label', value: 'workId' },
            },
          },
          {
            label: 'SPU商品',
            name: 'spuCode',
            type: 'Select',
            option: SpuOptions,
            placeholder: '款式编码/款式名称/助记码',
            config: {
              suffixIcon: null,
              showSearch: true,
              filterOption: false,
              optionFilterProp: 'label',
              onSearch: handleSearchSpuOptions,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
            },
          },
          {
            label: 'SKU商品',
            name: 'skuCodeList',
            placeholder: '商品条码',
            type: 'Select',
            option: SkuOptions,
            config: {
              mode: 'tags',
              maxTagCount: 'responsive',
              notFoundContent: null,
            },
          },
          {
            label: '推送状态',
            name: 'pushStatus',
            type: 'Select',
            option: PUSH_STATE_STATUS_OPTIONS,
            hidden: !isRoot,
          },
        ]}
        onFinish={(vals: any) => {
          setselectedRowKeys([])
          setselectedRowInfos([])
          const paramsData = {
            ...vals,
            createTimeStart: vals?.createTimeStart?.[0] && dayjs(vals.createTimeStart[0]).format('YYYY-MM-DD HH:mm:ss'),
            createTimeEnd: vals?.createTimeStart?.[1] && dayjs(vals.createTimeStart[1]).format('YYYY-MM-DD HH:mm:ss'),
            scheduleDeliveryTimeStart:
              vals?.scheduleDeliveryTimeStart?.[0] &&
              dayjs(vals.scheduleDeliveryTimeStart[0]).format('YYYY-MM-DD HH:mm:ss'),
            scheduleDeliveryTimeEnd:
              vals?.scheduleDeliveryTimeStart?.[1] &&
              dayjs(vals.scheduleDeliveryTimeStart[1]).format('YYYY-MM-DD HH:mm:ss'),
            estimatedArrivalTimeStart:
              vals?.estimatedArrivalTimeStart?.[0] &&
              dayjs(vals.estimatedArrivalTimeStart[0]).format('YYYY-MM-DD HH:mm:ss'),
            estimatedArrivalTimeEnd:
              vals?.estimatedArrivalTimeStart?.[1] &&
              dayjs(vals.estimatedArrivalTimeStart[1]).format('YYYY-MM-DD HH:mm:ss'),
            lastArrivalTimeStart:
              vals?.lastArrivalTimeStart?.[0] && dayjs(vals.lastArrivalTimeStart[0]).format('YYYY-MM-DD HH:mm:ss'),
            lastArrivalTimeEnd:
              vals?.lastArrivalTimeStart?.[1] && dayjs(vals.lastArrivalTimeStart[1]).format('YYYY-MM-DD HH:mm:ss'),
            reserveInvoiceStatuses: vals.reserveInvoiceStatuses?.length > 0 ? vals.reserveInvoiceStatuses : null,
            orderSources: vals.orderSources ? [vals.orderSources] : null,
            reserveInvoiceCodes: vals?.reserveInvoiceCodes?.length > 0 ? vals.reserveInvoiceCodes : null,
            purchaseOrderCodes: vals?.purchaseOrderCodes?.length > 0 ? vals.purchaseOrderCodes : null,
            year: vals.year ? vals.year : null,
            seasonCode: vals.seasonCode ? vals.seasonCode : null,
          }
          search(paramsData)
          setCachePage({
            ...paramsData,
            SupplierOption,
            SpuOptions,
            UserOptions,
            current: 1,
            size: params.size,
          })
        }}
        onReset={() => {
          setselectedRowKeys([])
          setselectedRowInfos([])
          const paramsData = {
            ...params,
            current: 1,
            size: 10,
            createTimeStart: dayjs(defaultDateRange[0]).format('YYYY-MM-DD HH:mm:ss'),
            createTimeEnd: dayjs(defaultDateRange[1]).format('YYYY-MM-DD HH:mm:ss'),
            reserveInvoiceStatuses: [1, 2, 3, 4, 6],
            reserveInvoiceCodes: null,
            purchaseOrderCodes: null,
          }
          setCachePage({
            ...paramsData,
          })
          reset()
        }}
        extra={
          <div className="table_extra_flex_wrapbox">
            <div className="table_extra_flex">
              <PermissionButton
                permission="deliver"
                type="primary"
                onClick={() => {
                  navigate('/purchase/delivery/add')
                }}
              >
                预约发货
              </PermissionButton>
              <PermissionButton
                permission="printBoxLabel"
                onClick={() => {
                  if (selectedRowKeys.length === 0) {
                    message.warning('请勾选需要操作的列表数据！')
                    return
                  }
                  const waitScanCodes = selectedRowInfos.filter((item) => item.reserveInvoiceStatus == 6)
                  if (waitScanCodes.length > 0) {
                    notification.warning({
                      message: '待扫码状态的预约发货单请前往【扫码装箱-箱唛】页面打印箱唛',
                      description: waitScanCodes?.map((item: any, index) => (
                        <div key={index}>{item?.reserveInvoiceCode}</div>
                      )),
                    })
                    return
                  }
                  const reserveInvoiceCodes = selectedRowInfos
                    ?.filter((item) => item.orderSource == 1)
                    ?.filter(
                      (item) =>
                        !(
                          item.reserveInvoiceStatus == 2 ||
                          item.reserveInvoiceStatus == 3 ||
                          item.reserveInvoiceStatus == 4
                        ),
                    )
                    ?.map((item) => item.reserveInvoiceCode)
                  if (reserveInvoiceCodes.length > 0) {
                    notification.warning({
                      message: '不符合打印条件',
                      description: reserveInvoiceCodes?.map((item: any, index) => <div key={index}>{item}</div>),
                    })
                    return
                  }
                  navigate('/print?type=3', {
                    state: {
                      params: selectedRowInfos.map((item) => item.reserveInvoiceCode),
                    },
                  })
                }}
              >
                打印箱唛
              </PermissionButton>
              <PermissionButton
                permission="checkDeliver"
                loading={exportLoading}
                onClick={async () => {
                  if (selectedRowKeys.length === 0) {
                    message.warning('请勾选需要操作的列表数据！')
                    return
                  }
                  const reserveInvoiceCodes = selectedRowInfos?.map((item) => item.reserveInvoiceCode)
                  setexportLoading(true)
                  const res = await reserveInvoiceBatchAudit({ reserveInvoiceCodes }).finally(() => {
                    setexportLoading(false)
                    setselectedRowKeys([])
                    setselectedRowInfos([])
                    search(params)
                  })
                  if (res.code === 200) {
                    message.success('操作成功')
                  }
                  if (res.code === 820000 && res.failInfo) {
                    const failInfo = JSON.parse(res.failInfo)?.map((item: string) => {
                      return <div key={item}>{item}</div>
                    })
                    notification.open({
                      type: 'warning',
                      message: res.msg,
                      description: failInfo,
                    })
                  }
                }}
              >
                发货审核
              </PermissionButton>
              <PermissionButton
                permission="printNotice"
                loading={exportLoading}
                onClick={async () => {
                  if (selectedRowKeys.length === 0) {
                    message.warning('请勾选需要操作的列表数据！')
                    return
                  }
                  const reserveInvoiceCodes = selectedRowInfos?.map((item) => item.reserveInvoiceCode)
                  setexportLoading(true)
                  const res = await exportOutNoticeOrder({ reserveInvoiceCodes }).finally(() => {
                    setexportLoading(false)
                    setselectedRowKeys([])
                    setselectedRowInfos([])
                  })
                  if (res.code === 200) {
                    downloadByOwnUrl(res.data)
                    message.success('操作成功')
                  }
                  if (res.code === 820000 && res.failInfo) {
                    const failInfo = JSON.parse(res.failInfo)?.map((item: string) => {
                      return <div key={item}>{item}</div>
                    })
                    notification.open({
                      type: 'warning',
                      message: res.msg,
                      description: failInfo,
                    })
                  }
                }}
              >
                打印出库通知单
              </PermissionButton>
              {isRoot && menuItems.length > 0 && (
                <Dropdown
                  placement="bottomLeft"
                  menu={{
                    items: menuItems,
                    onClick: handleClickMore,
                  }}
                >
                  <Button>
                    更多操作
                    <DownOutlined />
                  </Button>
                </Dropdown>
              )}
              <Checkbox
                onChange={(event: any) => {
                  setexpand(event.target.checked)
                }}
              >
                显示明细
              </Checkbox>
            </div>
            <div className="table_extra_flex">
              <PermissionButton
                permission="exportDeliver"
                onClick={async () => {
                  const paramsData: Record<string, any> = {}
                  if (selectedRowKeys.length > 0) {
                    paramsData.reserveInvoiceIds = selectedRowKeys
                  } else {
                    Object.assign(paramsData, params)
                  }
                  setexportLoading(true)
                  setspinning(true)
                  const res = await reserveInvoiceExport(paramsData)
                    .catch(() => setspinning(false))
                    .finally(() => {
                      setexportLoading(false)
                      setselectedRowKeys([])
                      setselectedRowInfos([])
                    })
                  if (res?.code === 200 && res?.data) {
                    await exportNotification(res?.data, navigate).finally(() => setspinning(false))
                  }
                }}
                icon={<UploadOutlined />}
                loading={exportLoading}
              >
                导出
              </PermissionButton>
            </div>
          </div>
        }
      ></SearchForm>
      <CustomTable
        bordered
        isSelection
        selectRows={selectRows}
        selectedRowKeys={selectedRowKeys}
        columns={useIndexColumns({ navigate, onView, onViewLogs, onConfirmDelivery, onSubmitPacking, onDel, isRoot })}
        {...tableProps}
        expandable={{
          expandedRowKeys,
          expandedRowRender,
          onExpandedRowsChange: (keys: React.Key[]) => {
            setexpandedRowKeys(keys)
          },
        }}
        rowKey={(rows) => rows.reserveInvoiceId}
        tableRowGray={(record) =>
          record.reserveInvoiceStatus && record.reserveInvoiceStatus == 5 ? 'table-row-gray' : ''
        }
        isScrollY
      />
      <LogsDrawer {...{ isLogShow, setisLogShow, logLoading, logInfos, setLogInfos }}></LogsDrawer>
      <Drawer
        title="确认发货"
        maskClosable
        open={deliveryModalShow}
        onClose={onCancel}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={onCancel}>取消</Button>
              <Button type="primary" onClick={() => FormDelivery.validateFields().then((values) => onDelivery(values))}>
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <EditFormVertical editConfig={useFormDelivery({ SupplierCYOption, getSupList })} form={FormDelivery} />
      </Drawer>
      <Drawer title="物流信息" maskClosable open={viewdeliveryModalShow} onClose={onCancel}>
        <EditFormVertical editConfig={useFormViewDelivery({ CurrentInfo })} form={FormViewDelivery} />
      </Drawer>
      <Modal title="预约发货" open={isModalShow} onCancel={onCancel} onOk={onSendOk}>
        <Form form={FormSend} layout="vertical">
          <Form.Item
            label="预约发货时间"
            name="scheduleDeliveryTime"
            style={{ marginBottom: 0 }}
            rules={[
              {
                required: true,
                message: '请选择预约发货时间',
              },
            ]}
          >
            <DatePicker showTime></DatePicker>
          </Form.Item>
        </Form>
      </Modal>
      <Spin spinning={spinning} fullscreen />
    </PageContainer>
  )
}

export default Index
